<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>多设备智能温控系统</title>
    <script src="./lib/tailwindcss.js"></script>
    <link href="./lib/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <script src="./lib/chart.umd.min.js"></script>
    <script src="./lib/crypto-js.min.js"></script>
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#FF7D00',
                        cold: '#4096ff',
                        hot: '#f5222d',
                        neutral: '#f5f5f5',
                        dark: '#1f2937'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .shadow-soft {
                box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            }
            .gradient-bg {
                background: linear-gradient(135deg, #f5f7fa 0%, #e5e9f2 100%);
            }
            .card-hover {
                transition: all 0.2s ease;
            }
            .card-hover:hover {
                transform: translateY(-3px);
            }
            .auto-refresh-indicator {
                animation: pulse 2s infinite;
            }
            .btn-press {
                transform: scale(0.95);
            }
            @keyframes pulse {
                0% { opacity: 0.6; }
                50% { opacity: 1; }
                100% { opacity: 0.6; }
            }
        }
    </style>
</head>
<body class="gradient-bg min-h-screen font-sans text-dark">
    <!-- 顶部导航栏 -->
    <header class="bg-white/90 backdrop-blur-md shadow-sm sticky top-0 z-50 transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-thermometer-half text-primary text-xl"></i>
                <h1 class="text-lg md:text-xl font-bold text-primary">智能温控系统</h1>
            </div>
            <div class="flex items-center space-x-3">
                <button id="account-selector" class="flex items-center text-sm px-2 py-1 rounded bg-primary/10 text-primary">
                    <i class="fa fa-user-o mr-1"></i>
                    <span id="current-account-name">自用</span>
                    <i class="fa fa-chevron-down ml-1 text-xs"></i>
                </button>
				
                
                <button id="refresh-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-refresh text-primary"></i>
                </button>
                <button id="settings-btn" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-cog text-primary"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 账号选择面板 -->
    <div id="account-panel" class="fixed inset-0 bg-black/50 z-50 flex items-start pt-20 px-4 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md mx-auto p-5 transform transition-all">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-bold text-primary">选择账号</h2>
                <button id="close-account-panel" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div id="accounts-list" class="space-y-2 max-h-[60vh] overflow-y-auto pr-2">
                <!-- 账号列表将通过JS动态生成 -->
                <div class="account-item active p-3 rounded-lg border border-primary bg-primary/5 flex justify-between items-center cursor-pointer">
                    <div class="flex items-center">
                        <i class="fa fa-user-circle text-primary mr-2"></i>
                        <span>自用</span>
                    </div>
                    <i class="fa fa-check text-primary"></i>
                </div>
            </div>
            
            <div class="mt-4 pt-4 border-t">
                <button id="add-account-btn" class="w-full py-2 border border-dashed border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-colors flex items-center justify-center">
                    <i class="fa fa-plus mr-2"></i> 添加新账号
                </button>
            </div>
        </div>
    </div>

    <!-- 设备选择面板 -->
    <div id="devices-panel" class="fixed inset-0 bg-black/50 z-50 flex items-start pt-20 px-4 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md mx-auto p-5 transform transition-all">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-bold text-primary">选择设备</h2>
                <button id="close-devices-panel" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div id="devices-list" class="space-y-2 max-h-[60vh] overflow-y-auto pr-2">
                <!-- 设备列表将通过JS动态生成 -->
            </div>
            
            <div class="mt-4 pt-4 border-t">
                <button id="add-device-btn" class="w-full py-2 border border-dashed border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-colors flex items-center justify-center">
                    <i class="fa fa-plus mr-2"></i> 添加新设备
                </button>
            </div>
        </div>
    </div>

    <!-- 设置面板 -->
    <div id="settings-panel" class="fixed inset-0 bg-black/50 z-50 flex items-start pt-20 px-4 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md mx-auto p-5 transform transition-all max-h-[80vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-bold text-primary">系统设置</h2>
                <button id="close-settings-panel" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-5">
                <div>
                    <h3 class="font-medium mb-3">账号管理</h3>
                    <button id="manage-accounts-btn" class="w-full py-2 px-3 rounded-lg text-left hover:bg-gray-50 transition-colors flex justify-between items-center">
                        <span>账号列表</span>
                        <i class="fa fa-chevron-right text-gray-400"></i>
                    </button>
                </div>
                
                <div>
                    <h3 class="font-medium mb-3">刷新设置</h3>
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-sm">自动刷新</span>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" id="auto-refresh-toggle" class="sr-only peer" checked>
                                <div class="w-10 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-primary"></div>
                            </label>
                        </div>
                        <div>
                            <span class="text-sm block mb-1">刷新间隔</span>
                            <select id="refresh-interval" class="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white">
                                <option value="10">10秒</option>
                                <option value="30" selected>30秒</option>
                                <option value="60">1分钟</option>
                                <option value="300">5分钟</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div>
                    <h3 class="font-medium mb-3">数据与隐私</h3>
                    <button id="export-all-config-btn" class="w-full py-2 px-3 rounded-lg text-left hover:bg-gray-50 transition-colors flex justify-between items-center">
                        <span>导出所有配置</span>
                        <i class="fa fa-download text-gray-400"></i>
                    </button>
                    <button id="import-all-config-btn" class="w-full py-2 px-3 rounded-lg text-left hover:bg-gray-50 transition-colors flex justify-between items-center">
                        <span>导入配置</span>
                        <i class="fa fa-upload text-gray-400"></i>
                    </button>
                    <input type="file" id="import-all-file" accept=".bafa-all" class="hidden">
                    <button id="clear-all-data-btn" class="w-full py-2 px-3 rounded-lg text-left hover:bg-gray-50 transition-colors text-red-500 flex justify-between items-center mt-1">
                        <span>清除所有数据</span>
                        <i class="fa fa-trash text-red-400"></i>
                    </button>
                </div>
                
                <div class="pt-2">
                    <button id="about-btn" class="w-full py-2 px-3 rounded-lg text-left hover:bg-gray-50 transition-colors flex justify-between items-center">
                        <span>关于</span>
                        <i class="fa fa-info-circle text-gray-400"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 账号配置面板 -->
    <div id="account-config-panel" class="fixed inset-0 bg-black/50 z-50 flex items-start pt-20 px-4 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md mx-auto p-5 transform transition-all">
            <div class="flex justify-between items-center mb-5">
                <h2 class="text-lg font-bold text-primary" id="account-config-title">添加新账号</h2>
                <button id="close-account-config" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <form id="account-config-form" class="space-y-4">
                <input type="hidden" id="account-id">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">账号名称 (便于识别)</label>
                    <input type="text" id="account-name" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="例如：家里的设备">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">巴法云ID (clientId)</label>
                    <input type="text" id="account-client-id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="88888888">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">API密钥</label>
                    <input type="password" id="account-api-key" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="你的API密钥">
                </div>
            </form>
            
            <div class="flex space-x-3 mt-6">
                <button id="delete-account-btn" class="flex-1 py-2 border border-red-300 text-red-500 rounded-lg hover:bg-red-50 transition-colors hidden">
                    <i class="fa fa-trash mr-1"></i> 删除账号
                </button>
                <button id="save-account-btn" class="flex-1 py-2 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors">
                    保存账号
                </button>
            </div>
        </div>
    </div>

    <!-- 设备配置面板 -->
    <div id="device-config-panel" class="fixed inset-0 bg-black/50 z-50 flex items-start pt-20 px-4 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md mx-auto p-5 transform transition-all">
            <div class="flex justify-between items-center mb-5">
                <h2 class="text-lg font-bold text-primary" id="device-config-title">添加新设备</h2>
                <button id="close-device-config" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <form id="device-config-form" class="space-y-4">
                <input type="hidden" id="device-id">
                <input type="hidden" id="device-account-id">
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">设备名称</label>
                    <input type="text" id="device-name" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="例如：客厅空调">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">温湿度主题</label>
                    <input type="text" id="device-temp-topic" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="temp004">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">空调主题</label>
                    <input type="text" id="device-air-topic" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="aircd005">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">设备位置</label>
                    <input type="text" id="device-location" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary transition-colors" placeholder="例如：客厅">
                </div>
            </form>
            
            <div class="flex space-x-3 mt-6">
                <button id="delete-device-btn" class="flex-1 py-2 border border-red-300 text-red-500 rounded-lg hover:bg-red-50 transition-colors hidden">
                    <i class="fa fa-trash mr-1"></i> 删除设备
                </button>
                <button id="save-device-btn" class="flex-1 py-2 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors">
                    保存设备
                </button>
            </div>
        </div>
    </div>

    <!-- 确认对话框 -->
    <div id="confirm-dialog" class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 hidden">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-md p-5 transform transition-all">
            <h3 class="text-lg font-bold text-center mb-3" id="confirm-title">确认操作</h3>
            <p class="text-gray-600 text-center mb-5" id="confirm-message">你确定要执行此操作吗？</p>
            <div class="flex space-x-3">
                <button id="confirm-cancel" class="flex-1 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                    取消
                </button>
                <button id="confirm-ok" class="flex-1 py-2 bg-red-500 text-white rounded-lg font-medium hover:bg-red-600 transition-colors">
                    确认
                </button>
            </div>
        </div>
    </div>

    <!-- 通知提示 -->
    <div id="notification" class="fixed bottom-6 left-1/2 transform -translate-x-1/2 bg-dark text-white px-6 py-3 rounded-lg shadow-lg transform translate-y-20 opacity-0 transition-all duration-300 flex items-center z-50 max-w-[80%]">
        <i id="notification-icon" class="fa fa-check-circle mr-2"></i>
        <span id="notification-text">操作成功</span>
    </div>

    <main class="container mx-auto px-4 py-5">
        <!-- 当前设备信息 -->
        <div class="bg-white rounded-2xl shadow-soft p-4 mb-4">
            <div class="flex justify-between items-center">
                <div class="flex items-center">
                    <div class="p-2 rounded-full bg-primary/10 mr-3">
                        <i class="fa fa-building-o text-primary"></i>
                    </div>
                    <div>
                        <h3 class="font-medium" id="current-account-display">自用</h3>
                        <p class="text-xs text-gray-500" id="current-client-id">巴法云 ID: 未配置</p>
                    </div>
                </div>
                <button id="switch-device-btn" class="text-primary text-sm flex items-center">
                    <span id="current-device-name">客厅空调</span>
                    <i class="fa fa-chevron-down ml-1 text-xs"></i>
                </button>
            </div>
        </div>

        <!-- 状态概览卡片 -->
        <div class="grid grid-cols-2 gap-4 mb-5">
            <!-- 温度卡片 -->
            <div class="bg-white rounded-2xl shadow-soft p-4 card-hover">
                <div class="flex justify-between items-start mb-3">
                    <div>
                        <h2 class="text-xs text-gray-500 font-medium">当前温度</h2>
                        <div class="flex items-end mt-1">
                            <span id="temperature" class="text-2xl font-bold">--</span>
                            <span class="text-lg font-bold ml-1">°C</span>
                        </div>
                    </div>
                    <div class="p-2 rounded-full bg-blue-50">
                        <i class="fa fa-thermometer-half text-primary"></i>
                    </div>
                </div>
                <div class="flex items-center text-xs text-gray-500">
                    <i class="fa fa-clock-o mr-1"></i>
                    <span id="temp-update-time">未更新</span>
                </div>
            </div>
            
            <!-- 湿度卡片 -->
            <div class="bg-white rounded-2xl shadow-soft p-4 card-hover">
                <div class="flex justify-between items-start mb-3">
                    <div>
                        <h2 class="text-xs text-gray-500 font-medium">当前湿度</h2>
                        <div class="flex items-end mt-1">
                            <span id="humidity" class="text-2xl font-bold">--</span>
                            <span class="text-lg font-bold ml-1">%</span>
                        </div>
                    </div>
                    <div class="p-2 rounded-full bg-green-50">
                        <i class="fa fa-tint text-green-500"></i>
                    </div>
                </div>
                <div class="flex items-center text-xs text-gray-500">
                    <i class="fa fa-clock-o mr-1"></i>
                    <span id="hum-update-time">未更新</span>
                </div>
            </div>
            
            <!-- 空调状态卡片 -->
            <div class="bg-white rounded-2xl shadow-soft p-4 card-hover col-span-2">
                <div class="flex justify-between items-start mb-3">
                    <div>
                        <h2 class="text-xs text-gray-500 font-medium">空调状态</h2>
                        <div class="mt-1">
                            <span id="ac-status" class="text-xl font-bold text-gray-400">未开启</span>
                            <div id="ac-details" class="text-gray-500 mt-1 text-sm hidden">
                                <div>模式: <span id="ac-mode">自动</span> | 温度: <span id="ac-temp">26°C</span> | 风速: <span id="ac-fan">自动</span></div>
                                <div class="text-xs mt-1">位置: <span id="device-location-display">客厅</span></div>
                            </div>
                        </div>
                    </div>
                    <div id="ac-icon" class="p-2 rounded-full bg-gray-50">
                        <i class="fa fa-snowflake-o text-gray-400"></i>
                    </div>
                </div>
                <div class="flex items-center text-xs text-gray-500">
                    <i class="fa fa-signal mr-1"></i>
                    <span id="connection-status">未连接</span>
                    <span id="auto-refresh-label" class="ml-2 text-xs text-gray-500 auto-refresh-indicator">(自动刷新中)</span>
                </div>
            </div>
        </div>
        
        <!-- 温湿度历史图表 -->
        <div class="bg-white rounded-2xl shadow-soft p-4 mb-5">
            <div class="flex justify-between items-center mb-3">
                <h2 class="text-sm font-semibold">温湿度趋势</h2>
                <div class="flex space-x-2">
                    <button class="chart-period-btn text-xs px-2 py-1 rounded-full bg-primary text-white" data-period="24h">24h</button>
                    <button class="chart-period-btn text-xs px-2 py-1 rounded-full bg-gray-100" data-period="7d">7d</button>
                    <button class="chart-period-btn text-xs px-2 py-1 rounded-full bg-gray-100" data-period="30d">30d</button>
                </div>
            </div>
            <div class="h-48">
                <canvas id="environment-chart"></canvas>
            </div>
        </div>
        
        <!-- 空调控制面板 -->
        <div class="bg-white rounded-2xl shadow-soft p-5 mb-5">
            <h2 class="text-sm font-semibold mb-4">空调控制</h2>
            
            <!-- 开关控制 -->
            <div class="flex items-center justify-between mb-6">
                <span class="text-sm font-medium">电源</span>
                <label class="relative inline-flex items-center cursor-pointer">
                    <input type="checkbox" id="ac-power" class="sr-only peer">
                    <div class="w-12 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                </label>
            </div>
            
            <!-- 模式选择 -->
            <div class="mb-6">
                <span class="text-sm font-medium block mb-2">运行模式</span>
                <div class="grid grid-cols-5 gap-2">
                    <button class="ac-mode-btn active" data-mode="auto">
                        <i class="fa fa-refresh block text-center text-sm mb-1"></i>
                        <span class="text-xs">自动</span>
                    </button>
                    <button class="ac-mode-btn" data-mode="cool">
                        <i class="fa fa-snowflake-o block text-center text-sm mb-1"></i>
                        <span class="text-xs">制冷</span>
                    </button>
                    <button class="ac-mode-btn" data-mode="dry">
                        <i class="fa fa-tint block text-center text-sm mb-1"></i>
                        <span class="text-xs">除湿</span>
                    </button>
                    <button class="ac-mode-btn" data-mode="fan">
                        <i class="fa fa-leaf block text-center text-sm mb-1"></i>
                        <span class="text-xs">通风</span>
                    </button>
                    <button class="ac-mode-btn" data-mode="heat">
                        <i class="fa fa-sun-o block text-center text-sm mb-1"></i>
                        <span class="text-xs">制热</span>
                    </button>
                </div>
            </div>
            
            <!-- 温度调节 -->
            <div class="mb-6">
                <span class="text-sm font-medium block mb-3">温度设置</span>
                <div class="flex items-center justify-center">
                    <button id="temp-down" class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-sm">
                        <i class="fa fa-minus"></i>
                    </button>
                    <div class="mx-6">
                        <span id="set-temperature" class="text-3xl font-bold">26</span>
                        <span class="text-lg">°C</span>
                    </div>
                    <button id="temp-up" class="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-sm">
                        <i class="fa fa-plus"></i>
                    </button>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2 mt-4">
                    <div id="temp-slider" class="bg-primary h-2 rounded-full" style="width: 50%"></div>
                </div>
                <div class="flex justify-between text-xs text-gray-500 mt-1">
                    <span>16°C</span>
                    <span>30°C</span>
                </div>
            </div>
            
            <!-- 风速调节 -->
            <div class="mb-6">
                <span class="text-sm font-medium block mb-2">风速设置</span>
                <div class="grid grid-cols-4 gap-2">
                    <button class="ac-fan-btn active" data-fan="auto">
                        <i class="fa fa-refresh block text-center text-sm mb-1"></i>
                        <span class="text-xs">自动</span>
                    </button>
                    <button class="ac-fan-btn" data-fan="low">
                        <i class="fa fa-wind block text-center text-sm mb-1"></i>
                        <span class="text-xs">低速</span>
                    </button>
                    <button class="ac-fan-btn" data-fan="medium">
                        <i class="fa fa-wind block text-center text-sm mb-1"></i>
                        <span class="text-xs">中速</span>
                    </button>
                    <button class="ac-fan-btn" data-fan="high">
                        <i class="fa fa-wind block text-center text-sm mb-1"></i>
                        <span class="text-xs">高速</span>
                    </button>
                </div>
            </div>
            
            <!-- 确认按钮 -->
            <div>
                <button id="send-command" class="w-full py-3 bg-primary text-white rounded-lg font-medium hover:bg-primary/90 transition-colors flex items-center justify-center">
                    <i class="fa fa-paper-plane mr-2"></i>
                    发送控制指令
                </button>
            </div>
        </div>
        
        <!-- 快速操作 -->
        <!--
		<div class="bg-white rounded-2xl shadow-soft p-4 mb-5">
            <h2 class="text-sm font-semibold mb-3">快速操作</h2>
            <div class="grid grid-cols-3 gap-3">
                <button class="quick-action-btn" data-action="sleep">
                    <i class="fa fa-moon-o block text-center text-lg mb-1"></i>
                    <span class="text-xs">睡眠模式</span>
                </button>
                <button class="quick-action-btn" data-action="away">
                    <i class="fa fa-suitcase block text-center text-lg mb-1"></i>
                    <span class="text-xs">离家模式</span>
                </button>
                <button class="quick-action-btn" data-action="eco">
                    <i class="fa fa-leaf block text-center text-lg mb-1"></i>
                    <span class="text-xs">节能模式</span>
                </button>
            </div>
        </div>
		-->
    </main>

    <footer class="py-4 text-center text-gray-500 text-xs mb-6">
        <p>多设备智能温控系统 © 2025</p>
    </footer>

    <script>
        // 数据模型
        const AppData = {
            accounts: [],
            currentAccountId: null,
            currentDeviceId: null,
            settings: {
                autoRefresh: true,
                refreshInterval: 30 // 秒
            },
            
            // 初始化数据
            init() {
                this.loadFromStorage();
                if (this.accounts.length === 0) {
                    // 添加默认账号
                    const defaultAccountId = this.generateId();
                    this.accounts.push({
                        id: defaultAccountId,
                        name: "自用",
                        clientId: "",
                        apiKey: "",
                        devices: [
                            {
                                id: this.generateId(),
                                name: "办公室空调",
                                tempTopic: "test004",
                                airTopic: "aircd005",
                                location: "办公室"
                            }
                        ]
                    });
                    this.currentAccountId = defaultAccountId;
                    this.currentDeviceId = this.accounts[0].devices[0].id;
                    this.saveToStorage();
                }
            },
            
            // 生成唯一ID
            generateId() {
                return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
            },
            
            // 获取当前账号
            getCurrentAccount() {
                return this.accounts.find(account => account.id === this.currentAccountId);
            },
            
            // 获取当前设备
            getCurrentDevice() {
                const account = this.getCurrentAccount();
                if (!account) return null;
                return account.devices.find(device => device.id === this.currentDeviceId);
            },
            
            // 添加账号
            addAccount(accountData) {
                const newAccount = {
                    id: this.generateId(),
                    name: accountData.name,
                    clientId: accountData.clientId,
                    apiKey: accountData.apiKey,
                    devices: []
                };
                this.accounts.push(newAccount);
                this.currentAccountId = newAccount.id;
                this.saveToStorage();
                return newAccount;
            },
            
            // 更新账号
            updateAccount(accountId, accountData) {
                const account = this.accounts.find(a => a.id === accountId);
                if (account) {
                    account.name = accountData.name;
                    account.clientId = accountData.clientId;
                    account.apiKey = accountData.apiKey;
                    this.saveToStorage();
                    return account;
                }
                return null;
            },
            
            // 删除账号
            deleteAccount(accountId) {
                const index = this.accounts.findIndex(a => a.id === accountId);
                if (index !== -1) {
                    this.accounts.splice(index, 1);
                    
                    // 如果删除的是当前账号，切换到第一个账号
                    if (this.currentAccountId === accountId) {
                        if (this.accounts.length > 0) {
                            this.currentAccountId = this.accounts[0].id;
                            this.currentDeviceId = this.accounts[0].devices[0]?.id || null;
                        } else {
                            this.currentAccountId = null;
                            this.currentDeviceId = null;
                        }
                    }
                    
                    this.saveToStorage();
                    return true;
                }
                return false;
            },
            
            // 添加设备
            addDevice(accountId, deviceData) {
                const account = this.accounts.find(a => a.id === accountId);
                if (account) {
                    const newDevice = {
                        id: this.generateId(),
                        name: deviceData.name,
                        tempTopic: deviceData.tempTopic,
                        airTopic: deviceData.airTopic,
                        location: deviceData.location || ""
                    };
                    account.devices.push(newDevice);
                    this.currentDeviceId = newDevice.id;
                    this.saveToStorage();
                    return newDevice;
                }
                return null;
            },
            
            // 更新设备
            updateDevice(accountId, deviceId, deviceData) {
                const account = this.accounts.find(a => a.id === accountId);
                if (account) {
                    const device = account.devices.find(d => d.id === deviceId);
                    if (device) {
                        device.name = deviceData.name;
                        device.tempTopic = deviceData.tempTopic;
                        device.airTopic = deviceData.airTopic;
                        device.location = deviceData.location || "";
                        this.saveToStorage();
                        return device;
                    }
                }
                return null;
            },
            
            // 删除设备
            deleteDevice(accountId, deviceId) {
                const account = this.accounts.find(a => a.id === accountId);
                if (account) {
                    const index = account.devices.findIndex(d => d.id === deviceId);
                    if (index !== -1) {
                        account.devices.splice(index, 1);
                        
                        // 如果删除的是当前设备，切换到第一个设备
                        if (this.currentDeviceId === deviceId) {
                            this.currentDeviceId = account.devices[0]?.id || null;
                        }
                        
                        this.saveToStorage();
                        return true;
                    }
                }
                return false;
            },
            
            // 保存到本地存储
            saveToStorage() {
                localStorage.setItem('thermostat_accounts', JSON.stringify(this.accounts));
                localStorage.setItem('thermostat_current_account', this.currentAccountId);
                localStorage.setItem('thermostat_current_device', this.currentDeviceId);
                localStorage.setItem('thermostat_settings', JSON.stringify(this.settings));
            },
            
            // 从本地存储加载
            loadFromStorage() {
                const accountsStr = localStorage.getItem('thermostat_accounts');
                const currentAccountId = localStorage.getItem('thermostat_current_account');
                const currentDeviceId = localStorage.getItem('thermostat_current_device');
                const settingsStr = localStorage.getItem('thermostat_settings');
                
                if (accountsStr) {
                    try {
                        this.accounts = JSON.parse(accountsStr);
                    } catch (e) {
                        console.error('加载账号数据失败', e);
                        this.accounts = [];
                    }
                }
                
                this.currentAccountId = currentAccountId;
                this.currentDeviceId = currentDeviceId;
                
                if (settingsStr) {
                    try {
                        this.settings = { ...this.settings, ...JSON.parse(settingsStr) };
                    } catch (e) {
                        console.error('加载设置失败', e);
                    }
                }
            },
            
            // 导出所有配置
            exportAllConfig(password) {
                const data = {
                    accounts: this.accounts,
                    currentAccountId: this.currentAccountId,
                    currentDeviceId: this.currentDeviceId,
                    settings: this.settings,
                    exportTime: new Date().toISOString()
                };
                
                if (!password || password.length < 6) {
                    throw new Error("加密密码至少需要6个字符");
                }
                
                return CryptoJS.AES.encrypt(JSON.stringify(data), password).toString();
            },
            
            // 导入所有配置
            importAllConfig(encryptedData, password) {
                try {
                    const bytes = CryptoJS.AES.decrypt(encryptedData, password);
                    const decryptedData = bytes.toString(CryptoJS.enc.Utf8);
                    const data = JSON.parse(decryptedData);
                    
                    if (data.accounts && Array.isArray(data.accounts)) {
                        this.accounts = data.accounts;
                        this.currentAccountId = data.currentAccountId;
                        this.currentDeviceId = data.currentDeviceId;
                        
                        if (data.settings) {
                            this.settings = { ...this.settings, ...data.settings };
                        }
                        
                        this.saveToStorage();
                        return true;
                    }
                    
                    throw new Error("导入的数据格式不正确");
                } catch (e) {
                    throw new Error("导入失败: " + e.message);
                }
            },
            
            // 清除所有数据
            clearAllData() {
                this.accounts = [];
                this.currentAccountId = null;
                this.currentDeviceId = null;
                this.settings = {
                    autoRefresh: true,
                    refreshInterval: 30
                };
                this.saveToStorage();
            }
        };

        // 巴法云API服务模块
        const BafaApiService = {
            config: {
                baseUrl: "https://apis.bemfa.com",
                endpoints: {
                    getData: "/va/getmsg",
                    publish: "/va/postJsonMsg",
                    getState: "/va/online"
                },
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Accept": "*/*"
                }
            },

            fetchData: async function(topic, apiKey) {
                const url = `${this.config.baseUrl}${this.config.endpoints.getData}?topic=${topic}&uid=${apiKey}&type=3`;
                
                try {
                    const response = await fetch(url);
                    if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
                    
                    const data = await response.json();
                    return this.parseDataResponse(data);
                } catch (error) {
                    console.error("获取数据失败:", error);
                    throw error;
                }
            },

            publishCommand: async function(command, config) {
                const url = `${this.config.baseUrl}${this.config.endpoints.publish}`;
    //console.log("826",url);
                const formData = JSON.stringify({
                    'uid': config.uid,
                    'topic': config.topic,
                    'msg': JSON.stringify(command),
                    'type': 3
                });
	//console.log("833",formData);
                try {
                    const response = await fetch(url, {
                        method: "POST",
                        headers: this.config.headers,
                        body: formData
                    });

                    if (!response.ok) throw new Error(`HTTP错误: ${response.status}`);
                    
					
                    const result = await response.json();
	//console.log("845",result);				
                    return this.parsePublishResponse(result);
                } catch (error) {
                    console.error("发送指令失败:", error);
                    throw error;
                }
            },

            checkState: async function(apiKey, topic) {
                const url = `${this.config.baseUrl}${this.config.endpoints.getState}?uid=${apiKey}&topic=${topic}&type=3`;
                
                try {
                    const response = await fetch(url);
                    return await response.text();
                } catch (error) {
                    console.error("检查状态失败:", error);
                    throw error;
                }
            },

            parseDataResponse: function(rawData) {
			
                if (rawData.code === 0 && rawData.data) {
                    return {
                        success: true,
                        data: rawData.data
                    };
                }
                return {
                    success: false,
                    error: rawData.msg || "未知错误"
                };
            },

            parsePublishResponse: function(rawResult) {
		//	console.log("880",rawResult);	
                if (rawResult.code === 0) {
                    return { success: true };
                }
                return {
                    success: false,
                    error: rawResult || "发布失败"
                };
            }
        };

        // 全局变量
        let currentTemp = 26;
        let currentMode = 'auto';
        let currentFan = 'auto';
        let isAcOn = false;
        let tempHistory = [];
        let humidityHistory = [];
        let timeLabels = [];
        let autoRefreshTimer = null;
        
        // DOM 元素获取
        const elements = {
            // 状态显示元素
            temperature: document.getElementById('temperature'),
            humidity: document.getElementById('humidity'),
            tempUpdateTime: document.getElementById('temp-update-time'),
            humUpdateTime: document.getElementById('hum-update-time'),
            acStatus: document.getElementById('ac-status'),
            acDetails: document.getElementById('ac-details'),
            acMode: document.getElementById('ac-mode'),
            acTemp: document.getElementById('ac-temp'),
            acFan: document.getElementById('ac-fan'),
            acIcon: document.getElementById('ac-icon'),
            setTemperature: document.getElementById('set-temperature'),
            tempSlider: document.getElementById('temp-slider'),
            acPower: document.getElementById('ac-power'),
            tempUp: document.getElementById('temp-up'),
            tempDown: document.getElementById('temp-down'),
            sendCommand: document.getElementById('send-command'),
            connectionStatus: document.getElementById('connection-status'),
            currentAccountName: document.getElementById('current-account-name'),
            currentAccountDisplay: document.getElementById('current-account-display'),
            currentClientId: document.getElementById('current-client-id'),
            currentDeviceName: document.getElementById('current-device-name'),
            deviceLocationDisplay: document.getElementById('device-location-display'),
            autoRefreshLabel: document.getElementById('auto-refresh-label'),
            
            // 面板元素
            accountPanel: document.getElementById('account-panel'),
            devicesPanel: document.getElementById('devices-panel'),
            settingsPanel: document.getElementById('settings-panel'),
            accountConfigPanel: document.getElementById('account-config-panel'),
            deviceConfigPanel: document.getElementById('device-config-panel'),
            confirmDialog: document.getElementById('confirm-dialog'),
            notification: document.getElementById('notification'),
            notificationIcon: document.getElementById('notification-icon'),
            notificationText: document.getElementById('notification-text'),
            
            // 列表容器
            accountsList: document.getElementById('accounts-list'),
            devicesList: document.getElementById('devices-list'),
            
            // 表单元素
            accountConfigForm: document.getElementById('account-config-form'),
            accountId: document.getElementById('account-id'),
            accountName: document.getElementById('account-name'),
            accountClientId: document.getElementById('account-client-id'),
            accountApiKey: document.getElementById('account-api-key'),
            accountConfigTitle: document.getElementById('account-config-title'),
            
            deviceConfigForm: document.getElementById('device-config-form'),
            deviceId: document.getElementById('device-id'),
            deviceAccountId: document.getElementById('device-account-id'),
            deviceName: document.getElementById('device-name'),
            deviceTempTopic: document.getElementById('device-temp-topic'),
            deviceAirTopic: document.getElementById('device-air-topic'),
            deviceLocation: document.getElementById('device-location'),
            deviceConfigTitle: document.getElementById('device-config-title'),
            
            autoRefreshToggle: document.getElementById('auto-refresh-toggle'),
            refreshInterval: document.getElementById('refresh-interval'),
            
            confirmTitle: document.getElementById('confirm-title'),
            confirmMessage: document.getElementById('confirm-message'),
            
            // 按钮元素
            accountSelector: document.getElementById('account-selector'),
            closeAccountPanel: document.getElementById('close-account-panel'),
            addAccountBtn: document.getElementById('add-account-btn'),
            closeAccountConfig: document.getElementById('close-account-config'),
            saveAccountBtn: document.getElementById('save-account-btn'),
            deleteAccountBtn: document.getElementById('delete-account-btn'),
            
            switchDeviceBtn: document.getElementById('switch-device-btn'),
            closeDevicesPanel: document.getElementById('close-devices-panel'),
            addDeviceBtn: document.getElementById('add-device-btn'),
            closeDeviceConfig: document.getElementById('close-device-config'),
            saveDeviceBtn: document.getElementById('save-device-btn'),
            deleteDeviceBtn: document.getElementById('delete-device-btn'),
            
            settingsBtn: document.getElementById('settings-btn'),
            closeSettingsPanel: document.getElementById('close-settings-panel'),
            manageAccountsBtn: document.getElementById('manage-accounts-btn'),
            exportAllConfigBtn: document.getElementById('export-all-config-btn'),
            importAllConfigBtn: document.getElementById('import-all-config-btn'),
            importAllFile: document.getElementById('import-all-file'),
            clearAllDataBtn: document.getElementById('clear-all-data-btn'),
            aboutBtn: document.getElementById('about-btn'),
            
            confirmCancel: document.getElementById('confirm-cancel'),
            confirmOk: document.getElementById('confirm-ok'),
            
            refreshBtn: document.getElementById('refresh-btn'),
            
            chartPeriodBtns: document.querySelectorAll('.chart-period-btn'),
            
            quickActionBtns: document.querySelectorAll('.quick-action-btn')
        };
        
        // 初始化图表
        const ctx = document.getElementById('environment-chart').getContext('2d');
        const envChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: timeLabels,
                datasets: [
                    {
                        label: '温度 (°C)',
                        data: tempHistory,
                        borderColor: '#165DFF',
                        backgroundColor: 'rgba(22, 93, 255, 0.1)',
                        tension: 0.4,
                        fill: true,
                        pointRadius: 2,
                        pointHoverRadius: 4
                    },
                    {
                        label: '湿度 (%)',
                        data: humidityHistory,
                        borderColor: '#36CFC9',
                        backgroundColor: 'rgba(54, 207, 201, 0.1)',
                        tension: 0.4,
                        fill: true,
                        pointRadius: 2,
                        pointHoverRadius: 4,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: false,
                        title: { display: true, text: '温度 (°C)', font: { size: 10 } },
                        ticks: { font: { size: 9 } }
                    },
                    y1: {
                        beginAtZero: true,
                        position: 'right',
                        title: { display: true, text: '湿度 (%)', font: { size: 10 } },
                        grid: { drawOnChartArea: false },
                        ticks: { font: { size: 9 } }
                    }
                },
                plugins: { 
                    legend: { 
                        position: 'top',
                        labels: {
                            boxWidth: 12,
                            font: { size: 10 }
                        }
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                interaction: {
                    mode: 'nearest',
                    axis: 'x',
                    intersect: false
                }
            }
        });
        
        // 工具函数
        function showNotification(message, isError = false) {
            elements.notificationText.textContent = message;
            
            if (isError) {
                elements.notificationIcon.className = 'fa fa-exclamation-circle mr-2';
                elements.notification.classList.remove('bg-dark');
                elements.notification.classList.add('bg-red-600');
            } else {
                elements.notificationIcon.className = 'fa fa-check-circle mr-2';
                elements.notification.classList.remove('bg-red-600');
                elements.notification.classList.add('bg-dark');
            }
            
            elements.notification.classList.remove('translate-y-20', 'opacity-0');
            elements.notification.classList.add('translate-y-0', 'opacity-100');
            
            setTimeout(() => {
                elements.notification.classList.remove('translate-y-0', 'opacity-100');
                elements.notification.classList.add('translate-y-20', 'opacity-0');
            }, 3000);
        }
        
        function showConfirmDialog(title, message, confirmCallback) {
            elements.confirmTitle.textContent = title;
            elements.confirmMessage.textContent = message;
            elements.confirmDialog.classList.remove('hidden');
            
            const cancelHandler = () => {
                elements.confirmDialog.classList.add('hidden');
                elements.confirmCancel.removeEventListener('click', cancelHandler);
                elements.confirmOk.removeEventListener('click', okHandler);
            };
            
            const okHandler = () => {
                confirmCallback();
                elements.confirmDialog.classList.add('hidden');
                elements.confirmCancel.removeEventListener('click', cancelHandler);
                elements.confirmOk.removeEventListener('click', okHandler);
            };
            
            elements.confirmCancel.addEventListener('click', cancelHandler);
            elements.confirmOk.addEventListener('click', okHandler);
        }
        
        // 初始化模拟数据
        function initMockData() {
            for (let i = 11; i >= 0; i--) {
                const now = new Date();
                now.setHours(now.getHours() - i);
                timeLabels.push(now.getHours() + ':00');
                
                const baseTemp = 25;
                const temp = (baseTemp + (Math.random() * 2 - 0.5)).toFixed(1);
                tempHistory.push(parseFloat(temp));
                
                const baseHum = 60;
                const hum = (baseHum + (Math.random() * 10 - 5)).toFixed(1);
                humidityHistory.push(parseFloat(hum));
            }
            
            envChart.data.labels = timeLabels;
            envChart.data.datasets[0].data = tempHistory;
            envChart.data.datasets[1].data = humidityHistory;
            envChart.update();
            updateCurrentValues();
        }
        
        // 更新当前温湿度显示
        function updateCurrentValues() {
            if (tempHistory.length > 0) {
                const lastTemp = tempHistory[tempHistory.length - 1];
                elements.temperature.textContent = lastTemp;
                
                if (lastTemp > 26) {
                    elements.temperature.classList.remove('text-cold', 'text-gray-700');
                    elements.temperature.classList.add('text-hot');
                } else if (lastTemp < 22) {
                    elements.temperature.classList.remove('text-hot', 'text-gray-700');
                    elements.temperature.classList.add('text-cold');
                } else {
                    elements.temperature.classList.remove('text-hot', 'text-cold');
                    elements.temperature.classList.add('text-gray-700');
                }
            }
            
            if (humidityHistory.length > 0) {
                elements.humidity.textContent = humidityHistory[humidityHistory.length - 1];
            }
            
            const now = new Date();
            const timeStr = now.toLocaleTimeString();
            elements.tempUpdateTime.textContent = `最后更新: ${timeStr}`;
            elements.humUpdateTime.textContent = `最后更新: ${timeStr}`;
        }
        
        // 添加新的模拟数据
        function addNewData() {
            const now = new Date();
            const timeStr = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
            
            if (timeLabels.length >= 12) {
                timeLabels.shift();
                tempHistory.shift();
                humidityHistory.shift();
            }
            
            timeLabels.push(timeStr);
            
            let lastTemp = tempHistory.length > 0 ? tempHistory[tempHistory.length - 1] : 25;
            const newTemp = (lastTemp + (Math.random() * 0.6 - 0.3)).toFixed(1);
            tempHistory.push(parseFloat(newTemp));
            
            let lastHum = humidityHistory.length > 0 ? humidityHistory[humidityHistory.length - 1] : 60;
            const newHum = (lastHum + (Math.random() * 2 - 1)).toFixed(1);
            humidityHistory.push(parseFloat(newHum));
            
            envChart.data.labels = timeLabels;
            envChart.data.datasets[0].data = tempHistory;
            envChart.data.datasets[1].data = humidityHistory;
            envChart.update();
            updateCurrentValues();
        }
        
        // 添加真实数据
        function addRealData(temp, hum) {
            const now = new Date();
            const timeStr = now.getHours() + ':' + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes();
            
            if (timeLabels.length >= 12) {
                timeLabels.shift();
                tempHistory.shift();
                humidityHistory.shift();
            }
            
            timeLabels.push(timeStr);
            tempHistory.push(temp);
            humidityHistory.push(hum);
            
            envChart.data.labels = timeLabels;
            envChart.data.datasets[0].data = tempHistory;
            envChart.data.datasets[1].data = humidityHistory;
            envChart.update();
            updateCurrentValues();
        }
        
        // 模式转换函数
        function modeToText(mode) {
            switch(mode) {
                case 'auto': return '自动';
                case 'cool': return '制冷';
                case 'dry': return '除湿';
                case 'fan': return '通风';
                case 'heat': return '制热';
                default: return '未知';
            }
        }
        
        function codeToMode(code) {
            const modeMap = { 
                '0': 'auto',
                '1': 'cool',
                '2': 'dry',
                '3': 'fan',
                '4': 'heat'
            };
            return modeMap[code] || 'auto';
        }
        
        function modeToCode(mode) {
            const modeMap = { 
                'auto': '0',
                'cool': '1',
                'dry': '2',
                'fan': '3',
                'heat': '4'
            };
            return modeMap[mode] || '0';
        }
        
        // 风扇模式转换函数
        function fanToText(fan) {
            switch(fan) {
                case 'auto': return '自动';
                case 'low': return '低速';
                case 'medium': return '中速';
                case 'high': return '高速';
                default: return '未知';
            }
        }
        
        function codeToFan(code) {
            const fanMap = { 
                '0': 'auto',
                '1': 'low',
                '2': 'medium',
                '3': 'high'
            };
            return fanMap[code] || 'auto';
        }
        
        function fanToCode(fan) {
            const fanMap = { 
                'auto': '0',
                'low': '1',
                'medium': '2',
                'high': '3'
            };
            return fanMap[fan] || '0';
        }
        
        // 更新空调状态显示
        function updateAcStatus() {
            const device = AppData.getCurrentDevice();
            if (device) {
                elements.deviceLocationDisplay.textContent = device.location || '未知位置';
            }
            
            if (isAcOn) {
                elements.acStatus.textContent = '运行中';
                elements.acStatus.classList.remove('text-gray-400');
                
                if (currentMode === 'auto') {
                    elements.acStatus.classList.remove('text-hot', 'text-green-500', 'text-blue-500', 'text-purple-500');
                    elements.acStatus.classList.add('text-gray-600');
                    elements.acIcon.innerHTML = '<i class="fa fa-refresh text-gray-600"></i>';
                    elements.acIcon.className = 'p-2 rounded-full bg-gray-50';
                } else if (currentMode === 'cool') {
                    elements.acStatus.classList.remove('text-hot', 'text-green-500', 'text-gray-600', 'text-purple-500');
                    elements.acStatus.classList.add('text-cold');
                    elements.acIcon.innerHTML = '<i class="fa fa-snowflake-o text-cold"></i>';
                    elements.acIcon.className = 'p-2 rounded-full bg-blue-50';
                } else if (currentMode === 'dry') {
                    elements.acStatus.classList.remove('text-hot', 'text-cold', 'text-gray-600', 'text-green-500');
                    elements.acStatus.classList.add('text-purple-500');
                    elements.acIcon.innerHTML = '<i class="fa fa-tint text-purple-500"></i>';
                    elements.acIcon.className = 'p-2 rounded-full bg-purple-50';
                } else if (currentMode === 'fan') {
                    elements.acStatus.classList.remove('text-hot', 'text-cold', 'text-gray-600', 'text-purple-500');
                    elements.acStatus.classList.add('text-green-500');
                    elements.acIcon.innerHTML = '<i class="fa fa-leaf text-green-500"></i>';
                    elements.acIcon.className = 'p-2 rounded-full bg-green-50';
                } else if (currentMode === 'heat') {
                    elements.acStatus.classList.remove('text-cold', 'text-green-500', 'text-gray-600', 'text-purple-500');
                    elements.acStatus.classList.add('text-hot');
                    elements.acIcon.innerHTML = '<i class="fa fa-sun-o text-hot"></i>';
                    elements.acIcon.className = 'p-2 rounded-full bg-red-50';
                }
                
                elements.acDetails.classList.remove('hidden');
                elements.acMode.textContent = modeToText(currentMode);
                elements.acTemp.textContent = currentTemp + '°C';
                elements.acFan.textContent = fanToText(currentFan);
            } else {
                elements.acStatus.textContent = '未开启';
                elements.acStatus.className = 'text-xl font-bold text-gray-400';
                elements.acIcon.innerHTML = '<i class="fa fa-snowflake-o text-gray-400"></i>';
                elements.acIcon.className = 'p-2 rounded-full bg-gray-50';
                elements.acDetails.classList.add('hidden');
            }
            
            elements.acPower.checked = isAcOn;
            elements.setTemperature.textContent = currentTemp;
            updateTemperatureDisplay();
            
            document.querySelectorAll('.ac-mode-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.mode === currentMode) btn.classList.add('active');
            });
            
            document.querySelectorAll('.ac-fan-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.dataset.fan === currentFan) btn.classList.add('active');
            });
        }
        
        // 更新温度显示
        function updateTemperatureDisplay() {
            elements.setTemperature.textContent = currentTemp;
            const percentage = ((currentTemp - 16) / (30 - 16)) * 100;
            elements.tempSlider.style.width = percentage + '%';
            
            if (isAcOn) {
                elements.acTemp.textContent = currentTemp + '°C';
            }
        }
        
        // 验证数据
        function validateEnvData(temp, hum) {
            return !isNaN(temp) && !isNaN(hum) && temp >= -10 && temp <= 50 && hum >= 0 && hum <= 100;
        }
        
        function validateAcData(acData) {
            if (!acData || !acData.power || !acData.mode || !acData.temp) return false;
            
            const temp = parseInt(acData.temp);
            if (isNaN(temp) || temp < 16 || temp > 30) return false;
            
            const mode = acData.mode.toString();
            if (!['0', '1', '2', '3', '4'].includes(mode)) return false;
            
            const fan = acData.fan ? acData.fan.toString() : '0';
            if (!['0', '1', '2', '3'].includes(fan)) return false;
            
            return true;
        }
        
        // 数据获取和发送函数
        async function fetchFromBafaCloud() {
			checkBafaConnection();
            const account = AppData.getCurrentAccount();
            const device = AppData.getCurrentDevice();
            
            if (!account || !device || !account.apiKey || !device.tempTopic) {
                elements.connectionStatus.textContent = "未配置设备";
                return;
            }
            
            try {
                elements.connectionStatus.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-yellow-500 inline-block mr-1 animate-pulse"></span>加载中';
                
                const result = await BafaApiService.fetchData(
                    device.tempTopic, 
                    account.apiKey
                );
                
                if (result.success && result.data) {
					const [,temperature,humidity,newStatus] = result.data[0].msg.split('#');
                    const newTemp = parseFloat(temperature);
                    const newHum = parseFloat(humidity);
                    
                    if (validateEnvData(newTemp, newHum)) {
                        addRealData(newTemp, newHum);
                        elements.connectionStatus.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block mr-1"></span>已连接';
                    } else {
                        throw new Error("获取到无效的温湿度数据");
                    }
                } else {
                    elements.connectionStatus.innerHTML = `<span class="w-1.5 h-1.5 rounded-full bg-red-500 inline-block mr-1"></span>${result.error}`;
                }
            } catch (error) {
                console.error("获取数据失败:", error);
                elements.connectionStatus.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-red-500 inline-block mr-1"></span>连接失败';
            }
        }
        
        async function fetchAirConditionerStatus() {
            const account = AppData.getCurrentAccount();
            const device = AppData.getCurrentDevice();
            
            if (!account || !device || !account.apiKey || !device.airTopic) {
                return;
            }
            checkBafaConnection();
            try {
                const result = await BafaApiService.fetchData(
                    device.airTopic, 
                    account.apiKey
                );
//console.log("1429",result);
                if (result.success && result.data && result.data[0].msg) {
                    const acData = JSON.parse(result.data[0].msg);
                    
                    if (validateAcData(acData)) {
                        isAcOn = acData.power === "1" || acData.power === 1;
                        currentMode = codeToMode(acData.mode);
                        currentTemp = parseInt(acData.temp) || 26;
                        currentFan = codeToFan(acData.fan);
                        updateAcStatus();
                    } else {
                        throw new Error("获取到无效的空调状态数据");
                    }
                }
            } catch (error) {
                console.error("获取空调状态错误:", error);
            }
        }
        
        async function sendAcCommand() {
            const account = AppData.getCurrentAccount();
            const device = AppData.getCurrentDevice();
            
            if (!account || !device) {
                showNotification("请先选择设备", true);
                return;
            }
            
            if (!account.clientId || !account.apiKey) {
                showNotification("请先配置巴法云账号信息", true);
                return;
            }
            
            if (!device.airTopic) {
                showNotification("请先配置空调主题", true);
                return;
            }

            const commandData = {
                power: isAcOn ? "1" : "0",
                mode: modeToCode(currentMode),
                temp: currentTemp.toString(),
                fan: fanToCode(currentFan),
                time: new Date().getTime()
            };

            const sendBtn = elements.sendCommand;
            const originalText = sendBtn.innerHTML;
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<i class="fa fa-circle-o-notch fa-spin mr-2"></i> 发送中...';
            sendBtn.classList.add('btn-press');

            try {
                const config = {
					uid: account.apiKey,
					topic: device.airTopic,
					type: 3
                };
                
                const result = await BafaApiService.publishCommand(commandData, config);
				
				//console.log(result);
                if (result.success) {
                    showNotification("控制指令发送成功");
                    // 发送成功后立即刷新状态
                    setTimeout(fetchAirConditionerStatus, 1000);
                } else {
                    showNotification(`发送失败: ${result.error}`, true);
                }
            } catch (error) {
                console.error("发送指令失败:", error);
                showNotification(`发送失败: ${error.message}`, true);
            } finally {
                sendBtn.disabled = false;
                sendBtn.innerHTML = originalText;
                sendBtn.classList.remove('btn-press');
            }
        }
        
        async function checkBafaConnection() {
            const account = AppData.getCurrentAccount();
            const device = AppData.getCurrentDevice();
            
            if (!account || !device || !account.apiKey || !device.tempTopic) return;
            
            try {
                const state = await BafaApiService.checkState(account.apiKey, device.tempTopic);
				var data =  JSON.parse(state);
	//console.log("1521",data.data);
                if (data.data) {
                    elements.connectionStatus.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-green-500 inline-block mr-1"></span>设备在线';
                } else {
                    elements.connectionStatus.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-yellow-500 inline-block mr-1"></span>设备离线';
                }
            } catch (error) {
                elements.connectionStatus.innerHTML = '<span class="w-1.5 h-1.5 rounded-full bg-red-500 inline-block mr-1"></span>连接失败';
            }
        }
        
        // 启动自动刷新
        function startAutoRefresh() {
            // 先清除已有的定时器
            stopAutoRefresh();
            
            // 如果开启了自动刷新
            if (AppData.settings.autoRefresh) {
                // 显示自动刷新指示器
                elements.autoRefreshLabel.style.display = 'inline';
                
                // 设置新的定时器
                const intervalMs = AppData.settings.refreshInterval * 1000;
                autoRefreshTimer = setInterval(() => {
                    console.log("自动刷新数据...");
                    fetchFromBafaCloud();
                    fetchAirConditionerStatus();
                }, intervalMs);
            } else {
                // 隐藏自动刷新指示器
                elements.autoRefreshLabel.style.display = 'none';
            }
        }
        
        // 停止自动刷新
        function stopAutoRefresh() {
            if (autoRefreshTimer) {
                clearInterval(autoRefreshTimer);
                autoRefreshTimer = null;
            }
        }
        
        // 渲染账号列表
        function renderAccountsList() {
            elements.accountsList.innerHTML = '';
            
            AppData.accounts.forEach(account => {
                const isActive = AppData.currentAccountId === account.id;
                const accountItem = document.createElement('div');
                accountItem.className = `account-item p-3 rounded-lg border ${isActive ? 'border-primary bg-primary/5' : 'border-transparent hover:border-gray-200'} flex justify-between items-center cursor-pointer`;
                accountItem.innerHTML = `
                    <div class="flex items-center">
                        <i class="fa fa-user-circle ${isActive ? 'text-primary' : 'text-gray-500'} mr-2"></i>
                        <span>${account.name}</span>
                    </div>
                    ${isActive ? '<i class="fa fa-check text-primary"></i>' : ''}
                `;
                
                accountItem.addEventListener('click', () => {
                    AppData.currentAccountId = account.id;
                    // 如果该账号有设备，选择第一个设备
                    if (account.devices.length > 0) {
                        AppData.currentDeviceId = account.devices[0].id;
                    } else {
                        AppData.currentDeviceId = null;
                    }
                    AppData.saveToStorage();
                    updateUI();
                    elements.accountPanel.classList.add('hidden');
                    showNotification(`已切换到 ${account.name}`);
                    
                    // 刷新数据
                    fetchFromBafaCloud();
                    fetchAirConditionerStatus();
                });
                
                elements.accountsList.appendChild(accountItem);
            });
        }
        
        // 渲染设备列表
        function renderDevicesList() {
            const account = AppData.getCurrentAccount();
            if (!account) {
                elements.devicesList.innerHTML = '<div class="text-center text-gray-500 py-6">请先选择账号</div>';
                return;
            }
            
            elements.devicesList.innerHTML = '';
            
            if (account.devices.length === 0) {
                elements.devicesList.innerHTML = '<div class="text-center text-gray-500 py-6">该账号暂无设备，请添加设备</div>';
                return;
            }
            
            account.devices.forEach(device => {
                const isActive = AppData.currentDeviceId === device.id;
                const deviceItem = document.createElement('div');
                deviceItem.className = `device-item p-3 rounded-lg border ${isActive ? 'border-primary bg-primary/5' : 'border-transparent hover:border-gray-200'} flex justify-between items-center cursor-pointer`;
                deviceItem.innerHTML = `
                    <div>
                        <div class="font-medium">${device.name}</div>
                        <div class="text-xs text-gray-500">${device.location || '未设置位置'}</div>
                    </div>
                    ${isActive ? '<i class="fa fa-check text-primary"></i>' : ''}
                `;
                
                deviceItem.addEventListener('click', () => {
                    AppData.currentDeviceId = device.id;
                    AppData.saveToStorage();
                    updateUI();
                    elements.devicesPanel.classList.add('hidden');
                    showNotification(`已选择 ${device.name}`);
                    
                    // 刷新数据
                    fetchFromBafaCloud();
                    fetchAirConditionerStatus();
                });
                
                elements.devicesList.appendChild(deviceItem);
            });
        }
        
        // 打开账号配置面板
        function openAccountConfig(accountId = null) {
            const account = accountId ? AppData.accounts.find(a => a.id === accountId) : null;
            
            if (account) {
                elements.accountId.value = account.id;
                elements.accountName.value = account.name;
                elements.accountClientId.value = account.clientId;
                elements.accountApiKey.value = account.apiKey;
                elements.accountConfigTitle.textContent = '编辑账号';
                elements.deleteAccountBtn.classList.remove('hidden');
            } else {
                elements.accountConfigForm.reset();
                elements.accountId.value = '';
                elements.accountConfigTitle.textContent = '添加新账号';
                elements.deleteAccountBtn.classList.add('hidden');
            }
            
            elements.accountPanel.classList.add('hidden');
            elements.accountConfigPanel.classList.remove('hidden');
        }
        
        // 打开设备配置面板
        function openDeviceConfig(deviceId = null) {
            const account = AppData.getCurrentAccount();
            if (!account) {
                showNotification("请先选择账号", true);
                return;
            }
            
            const device = deviceId ? account.devices.find(d => d.id === deviceId) : null;
            
            if (device) {
                elements.deviceId.value = device.id;
                elements.deviceAccountId.value = account.id;
                elements.deviceName.value = device.name;
                elements.deviceTempTopic.value = device.tempTopic;
                elements.deviceAirTopic.value = device.airTopic;
                elements.deviceLocation.value = device.location;
                elements.deviceConfigTitle.textContent = '编辑设备';
                elements.deleteDeviceBtn.classList.remove('hidden');
            } else {
                elements.deviceConfigForm.reset();
                elements.deviceId.value = '';
                elements.deviceAccountId.value = account.id;
                elements.deviceConfigTitle.textContent = '添加新设备';
                elements.deleteDeviceBtn.classList.add('hidden');
            }
            
            elements.devicesPanel.classList.add('hidden');
            elements.deviceConfigPanel.classList.remove('hidden');
        }
        
        // 保存账号配置
        function saveAccountConfig() {
            const accountId = elements.accountId.value;
            const name = elements.accountName.value.trim();
            const clientId = elements.accountClientId.value.trim();
            const apiKey = elements.accountApiKey.value.trim();
            
            if (!name) {
                showNotification("请输入账号名称", true);
                return;
            }
            
            if (accountId) {
                // 更新现有账号
                AppData.updateAccount(accountId, { name, clientId, apiKey });
                showNotification("账号已更新");
            } else {
                // 添加新账号
                AppData.addAccount({ name, clientId, apiKey });
                showNotification("新账号已添加");
            }
            
            renderAccountsList();
            updateUI();
            elements.accountConfigPanel.classList.add('hidden');
        }
        
        // 保存设备配置
        function saveDeviceConfig() {
            const deviceId = elements.deviceId.value;
            const accountId = elements.deviceAccountId.value;
            const name = elements.deviceName.value.trim();
            const tempTopic = elements.deviceTempTopic.value.trim();
            const airTopic = elements.deviceAirTopic.value.trim();
            const location = elements.deviceLocation.value.trim();
            
            if (!name) {
                showNotification("请输入设备名称", true);
                return;
            }
            
            if (!tempTopic) {
                showNotification("请输入温湿度主题", true);
                return;
            }
            
            if (!airTopic) {
                showNotification("请输入空调主题", true);
                return;
            }
            
            if (deviceId) {
                // 更新现有设备
                AppData.updateDevice(accountId, deviceId, { name, tempTopic, airTopic, location });
                showNotification("设备已更新");
            } else {
                // 添加新设备
                AppData.addDevice(accountId, { name, tempTopic, airTopic, location });
                showNotification("新设备已添加");
            }
            
            renderDevicesList();
            updateUI();
            elements.deviceConfigPanel.classList.add('hidden');
        }
        
        // 删除账号
        function deleteAccount() {
            const accountId = elements.accountId.value;
            if (!accountId) return;
            
            const account = AppData.accounts.find(a => a.id === accountId);
            if (!account) return;
            
            showConfirmDialog(
                "删除账号",
                `确定要删除账号"${account.name}"吗？该账号下的所有设备也将被删除。`,
                () => {
                    AppData.deleteAccount(accountId);
                    renderAccountsList();
                    updateUI();
                    elements.accountConfigPanel.classList.add('hidden');
                    showNotification("账号已删除");
                }
            );
        }
        
        // 删除设备
        function deleteDevice() {
            const deviceId = elements.deviceId.value;
            const accountId = elements.deviceAccountId.value;
            if (!deviceId || !accountId) return;
            
            const account = AppData.accounts.find(a => a.id === accountId);
            if (!account) return;
            
            const device = account.devices.find(d => d.id === deviceId);
            if (!device) return;
            
            showConfirmDialog(
                "删除设备",
                `确定要删除设备"${device.name}"吗？`,
                () => {
                    AppData.deleteDevice(accountId, deviceId);
                    renderDevicesList();
                    updateUI();
                    elements.deviceConfigPanel.classList.add('hidden');
                    showNotification("设备已删除");
                }
            );
        }
        
        // 导出所有配置
        function exportAllConfig() {
            const password = prompt("请设置加密密码（至少6个字符）：");
            if (!password) return;
            
            try {
                const encryptedData = AppData.exportAllConfig(password);
                const blob = new Blob([encryptedData], { type: 'application/octet-stream' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `thermostat_config_${new Date().getTime()}.bafa-all`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                showNotification("配置已加密导出");
            } catch (error) {
                showNotification(error.message, true);
            }
        }
        
        // 导入所有配置
        function importAllConfig(file) {
            const password = prompt("请输入加密密码：");
            if (!password) return;
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const success = AppData.importAllConfig(e.target.result, password);
                    if (success) {
                        renderAccountsList();
                        renderDevicesList();
                        updateUI();
                        showNotification("配置已成功导入并应用");
                        
                        // 重启自动刷新
                        startAutoRefresh();
                        
                        // 刷新数据
                        fetchFromBafaCloud();
                        fetchAirConditionerStatus();
                    }
                } catch (error) {
                    showNotification(error.message, true);
                }
            };
            reader.readAsText(file);
        }
        
        // 清除所有数据
        function clearAllData() {
            showConfirmDialog(
                "清除所有数据",
                "确定要清除所有账号、设备和设置数据吗？此操作不可恢复。",
                () => {
                    AppData.clearAllData();
                    AppData.init(); // 重新初始化默认数据
                    renderAccountsList();
                    renderDevicesList();
                    updateUI();
                    elements.settingsPanel.classList.add('hidden');
                    showNotification("所有数据已清除");
                    
                    // 重启自动刷新
                    startAutoRefresh();
                }
            );
        }
        
        // 更新UI显示
        function updateUI() {
            const account = AppData.getCurrentAccount();
            const device = AppData.getCurrentDevice();
            
            // 更新账号显示
            if (account) {
                elements.currentAccountName.textContent = account.name;
                elements.currentAccountDisplay.textContent = account.name;
                elements.currentClientId.textContent = `巴法云 ID: ${account.clientId || '未配置'}`;
            } else {
                elements.currentAccountName.textContent = "无账号";
                elements.currentAccountDisplay.textContent = "无账号";
                elements.currentClientId.textContent = "巴法云 ID: 未配置";
            }
            
            // 更新设备显示
            if (device) {
                elements.currentDeviceName.textContent = device.name;
                elements.deviceLocationDisplay.textContent = device.location || '未知位置';
            } else {
                elements.currentDeviceName.textContent = "无设备";
                elements.deviceLocationDisplay.textContent = "未知位置";
            }
            
            // 更新设置面板
            elements.autoRefreshToggle.checked = AppData.settings.autoRefresh;
            elements.refreshInterval.value = AppData.settings.refreshInterval;
            
            // 更新空调状态
            updateAcStatus();
        }
        
        // 快速操作
        function applyQuickAction(action) {
            switch(action) {
                case 'sleep':
                    // 睡眠模式：26度，自动模式，低速风
                    currentTemp = 26;
                    currentMode = 'auto';
                    currentFan = 'low';
                    isAcOn = true;
                    break;
                case 'away':
                    // 离家模式：28度，自动模式，自动风
                    currentTemp = 28;
                    currentMode = 'auto';
                    currentFan = 'auto';
                    isAcOn = true;
                    break;
                case 'eco':
                    // 节能模式：27度，自动模式，低速风
                    currentTemp = 27;
                    currentMode = 'auto';
                    currentFan = 'low';
                    isAcOn = true;
                    break;
            }
            
            updateAcStatus();
            sendAcCommand();
        }
        
        // 事件监听器设置
        function setupEventListeners() {
            // 账号面板相关
            elements.accountSelector.addEventListener('click', () => {
                renderAccountsList();
                elements.accountPanel.classList.remove('hidden');
            });
            
            elements.closeAccountPanel.addEventListener('click', () => {
                elements.accountPanel.classList.add('hidden');
            });
            
            elements.addAccountBtn.addEventListener('click', () => {
                openAccountConfig();
            });
            
            // 账号配置相关
            elements.closeAccountConfig.addEventListener('click', () => {
                elements.accountConfigPanel.classList.add('hidden');
            });
            
            elements.saveAccountBtn.addEventListener('click', saveAccountConfig);
            
            elements.deleteAccountBtn.addEventListener('click', deleteAccount);
            
            // 设备面板相关
            elements.switchDeviceBtn.addEventListener('click', () => {
                renderDevicesList();
                elements.devicesPanel.classList.remove('hidden');
            });
            
            elements.closeDevicesPanel.addEventListener('click', () => {
                elements.devicesPanel.classList.add('hidden');
            });
            
            elements.addDeviceBtn.addEventListener('click', () => {
                openDeviceConfig();
            });
            
            // 设备配置相关
            elements.closeDeviceConfig.addEventListener('click', () => {
                elements.deviceConfigPanel.classList.add('hidden');
            });
            
            elements.saveDeviceBtn.addEventListener('click', saveDeviceConfig);
            
            elements.deleteDeviceBtn.addEventListener('click', deleteDevice);
            
            // 设置面板相关
            elements.settingsBtn.addEventListener('click', () => {
                elements.settingsPanel.classList.remove('hidden');
            });
            
            elements.closeSettingsPanel.addEventListener('click', () => {
                elements.settingsPanel.classList.add('hidden');
            });
            
            elements.manageAccountsBtn.addEventListener('click', () => {
                renderAccountsList();
                elements.settingsPanel.classList.add('hidden');
                elements.accountPanel.classList.remove('hidden');
            });
            
            // 配置导入导出
            elements.exportAllConfigBtn.addEventListener('click', exportAllConfig);
            
            elements.importAllConfigBtn.addEventListener('click', () => {
                elements.importAllFile.click();
            });
            
            elements.importAllFile.addEventListener('change', (e) => {
                if (e.target.files && e.target.files[0]) {
                    importAllConfig(e.target.files[0]);
                    e.target.value = '';
                }
            });
            
            elements.clearAllDataBtn.addEventListener('click', clearAllData);
            
            elements.aboutBtn.addEventListener('click', () => {
                alert('多设备智能温控系统 v1.0\n\n支持多巴法云账号和多空调管理的智能温控解决方案');
            });
            
            // 自动刷新设置
            elements.autoRefreshToggle.addEventListener('change', () => {
                AppData.settings.autoRefresh = elements.autoRefreshToggle.checked;
                AppData.saveToStorage();
                startAutoRefresh();
            });
            
            elements.refreshInterval.addEventListener('change', () => {
                AppData.settings.refreshInterval = parseInt(elements.refreshInterval.value);
                AppData.saveToStorage();
                startAutoRefresh();
            });
            
            // 温度调节
            elements.tempUp.addEventListener('click', () => {
                if (currentTemp < 30) {
                    currentTemp++;
                    updateTemperatureDisplay();
                }
            });
            
            elements.tempDown.addEventListener('click', () => {
                if (currentTemp > 16) {
                    currentTemp--;
                    updateTemperatureDisplay();
                }
            });
            
            // 空调电源
            elements.acPower.addEventListener('change', () => {
                isAcOn = elements.acPower.checked;
                updateAcStatus();
            });
            
            // 模式选择
            document.querySelectorAll('.ac-mode-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    document.querySelectorAll('.ac-mode-btn').forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    currentMode = btn.dataset.mode;
                    updateAcStatus();
                });
            });
            
            // 风速选择
            document.querySelectorAll('.ac-fan-btn').forEach(btn => {
                btn.addEventListener('click', () => {
                    document.querySelectorAll('.ac-fan-btn').forEach(b => b.classList.remove('active'));
                    btn.classList.add('active');
                    currentFan = btn.dataset.fan;
                    updateAcStatus();
                });
            });
            
            // 发送指令
            elements.sendCommand.addEventListener('click', sendAcCommand);
            
            // 刷新按钮
            elements.refreshBtn.addEventListener('click', () => {
                const icon = elements.refreshBtn.querySelector('i');
                icon.classList.add('fa-spin');
                
                fetchFromBafaCloud();
                fetchAirConditionerStatus();
                
                setTimeout(() => {
                    icon.classList.remove('fa-spin');
                }, 1000);
            });
            
            // 图表周期选择
            elements.chartPeriodBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    elements.chartPeriodBtns.forEach(b => {
                        b.classList.remove('bg-primary', 'text-white');
                        b.classList.add('bg-gray-100');
                    });
                    btn.classList.remove('bg-gray-100');
                    btn.classList.add('bg-primary', 'text-white');
                    
                    // 这里可以根据选择的周期加载不同的数据
                    const period = btn.dataset.period;
                    console.log(`切换图表周期到 ${period}`);
                    // 实际应用中应该根据周期从服务器加载数据
                    showNotification(`已切换到${period === '24h' ? '24小时' : period === '7d' ? '7天' : '30天'}数据`);
                });
            });
            
            // 快速操作按钮
            elements.quickActionBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    const action = btn.dataset.action;
                    btn.classList.add('btn-press');
                    setTimeout(() => {
                        btn.classList.remove('btn-press');
                    }, 200);
                    applyQuickAction(action);
                });
            });
            
            // 点击面板外部关闭
            elements.accountPanel.addEventListener('click', (e) => {
                if (e.target === elements.accountPanel) {
                    elements.accountPanel.classList.add('hidden');
                }
            });
            
            elements.devicesPanel.addEventListener('click', (e) => {
                if (e.target === elements.devicesPanel) {
                    elements.devicesPanel.classList.add('hidden');
                }
            });
            
            elements.settingsPanel.addEventListener('click', (e) => {
                if (e.target === elements.settingsPanel) {
                    elements.settingsPanel.classList.add('hidden');
                }
            });
            
            elements.accountConfigPanel.addEventListener('click', (e) => {
                if (e.target === elements.accountConfigPanel) {
                    elements.accountConfigPanel.classList.add('hidden');
                }
            });
            
            elements.deviceConfigPanel.addEventListener('click', (e) => {
                if (e.target === elements.deviceConfigPanel) {
                    elements.deviceConfigPanel.classList.add('hidden');
                }
            });
            
            // 页面关闭前清理
            window.addEventListener('beforeunload', () => {
                stopAutoRefresh();
            });
        }
        
        // 初始化应用
        function initApp() {
            AppData.init();
            initMockData();
            setupEventListeners();
            updateUI();
            startAutoRefresh();
            
            // 初始加载数据
            setTimeout(() => {
                fetchFromBafaCloud();
                fetchAirConditionerStatus();
            }, 1000);
            
            // 添加自定义样式
            const style = document.createElement('style');
            style.textContent = `
                .ac-mode-btn, .ac-fan-btn, .quick-action-btn {
                    background-color: #f5f5f5;
                    border: none;
                    border-radius: 8px;
                    padding: 8px 5px;
                    transition: all 0.2s ease;
                    cursor: pointer;
                }
                
                .ac-mode-btn.active, .ac-fan-btn.active {
                    background-color: #e8f3ff;
                    color: #165DFF;
                    font-weight: 500;
                }
                
                .ac-mode-btn:hover, .ac-fan-btn:hover, .quick-action-btn:hover {
                    background-color: #e5e7eb;
                }
                
                .chart-period-btn {
                    transition: all 0.2s ease;
                }
                
                #temp-up:hover, #temp-down:hover {
                    background-color: #e5e7eb;
                }
                
                .btn-press {
                    transform: scale(0.95);
                }
            `;
            document.head.appendChild(style);
        }
        
        // 启动应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>
